<?php

namespace app\controller;
use app\BaseController;
use app\model\Category as CategoryModel;
use app\model\Goods as GoodsModel;
use app\model\TaobaoGoods as TaobaoGoodsModel;
use app\model\TaobaoGoodsArchive as TaobaoGoodsArchiveModel;
use app\model\Brand as BrandModel;
use app\model\Shop as ShopModel;
use app\service\DtkService;
use app\service\GoodsService;
use think\App;

class Data extends BaseController
{
    private $goodsModel;
    private $goodsService;
    private $tbGoodsModel;
    private $tbGoodsArchiveModel;
    private $categoryModel;
    private $brandModel;
    private $shopModel;
    private $appKey;
    private $appSecret;
    private $dtkService;

    public function __construct(App $app){
        parent::__construct($app);
        $this->goodsModel = app()->make(GoodsModel::class);
        $this->tbGoodsModel = app()->make(TaobaoGoodsModel::class);
        $this->tbGoodsArchiveModel = app()->make(TaobaoGoodsArchiveModel::class);
        $this->categoryModel = app()->make(CategoryModel::class);
        $this->brandModel = app()->make(BrandModel::class);
        $this->shopModel = app()->make(ShopModel::class);
        $this->goodsService = app()->make(GoodsService::class);
        $this->dtkService = app()->make(DtkService::class);
        $this->appKey = '5d5cdeab9bd59';
        $this->appSecret = '76ee11fe001c5698bdca0c7a802c0747';
    }
    public function grabTopGoods() {
        set_time_limit(0);
        $client = new \GetRankingList();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v1.3.1');
        //参数
        $params = array();
        $params['pageSize'] = 20;
        $rankType = !empty($this->request->get('r')) ? $this->request->get('r'): 1;
        $total = !empty($this->request->get('t')) ? $this->request->get('t'): 0;
        $p = !empty($this->request->get('p')) ? $this->request->get('p'): 1;
        while (true){
            $params['rankType'] = $rankType;
            while(true){
                $params['pageId'] = $p;
                $result = $client->setParams($params)->request();
                //print_r($result);exit();
                $request = json_decode($result, true);
                if (!is_null($request['data']) && !empty($request['data'])) {
                    for ($i = 0; $i < count($request['data']); $i++) {
                        $data['rank_type'] = $rankType;
                        $data['goods_id'] = $request['data'][$i]['goodsId'];//商品id
                        $data['name'] = $request['data'][$i]['title'];//名称
                        if($data['name']== ''){
                            continue;
                        }
                        $data['pic_url'] = trim($request['data'][$i]['mainPic']);//图片地址
                        $data['item_url'] = trim($request['data'][$i]['couponLink']);//商品详情地址
                        //$data['cat'] = "";
                        $data['click_url'] = trim($request['data'][$i]['couponLink']);//推广链接
                        $data['price'] = trim($request['data'][$i]['originalPrice']);//价格
                        $data['sales_volume'] = trim($request['data'][$i]['monthSales']);//销量
                        $data['commission_rate'] = trim($request['data'][$i]['commissionRate']);//佣金比例
                        $data['commission'] = $request['data'][$i]['actualPrice'] * $request['data'][$i]['commissionRate'] / 100;//佣金
                        $data['wangwang'] = '';//$request['data'][$i]['guideName'];//卖家旺旺
                        $data['wangwang_id'] = trim($request['data'][$i]['sellerId']);
                        $data['shop_name'] = $request['data'][$i]['shopName'];//店铺名
                        $data['shop_type'] = $request['data'][$i]["shopType"];
                        //$data['coupon_id'] = trim($request['data'][$i][15]);
                        $data['coupon_total'] = trim($request['data'][$i]['couponTotalNum']);
                        $data['coupon_surplus'] = $request['data'][$i]['couponTotalNum'] - $request['data'][$i]['couponReceiveNum'];
                        $data['coupon_price'] = $request['data'][$i]['actualPrice'];
                        $data['coupon_start'] = $request['data'][$i]['couponStartTime'];
                        $data['coupon_end'] = $request['data'][$i]['couponEndTime'];
                        if ($data['coupon_end'] < date('Y-m-d', time())) {
                            continue;
                        }
                        $data['coupon_money'] = $request['data'][$i]['couponPrice'];
                        $data['coupon_url'] = $request['data'][$i]['couponLink'];
                        $data['coupon_click_url'] = $request['data'][$i]['couponLink'];
                        $data['import_date'] = date('Y-m-d',time());
                        $data['create_time'] = date('Y-m-d H:i:s',time());
                        $data['update_time'] = date('Y-m-d H:i:s',time());
                        //print_r($data);exit;
                        $where['goods_id'] = $data['goods_id'];
                        $oneGoods = $this->tbGoodsModel->where($where)->find();
                        if (empty($oneGoods)) {
                            $this->tbGoodsModel->insert($data);
                            $total ++;
                        } else {
                            $this->tbGoodsModel->where($where)->save($data);
                        }
                    }
                }
                if ($p >= 10) {
                    break;
                }
                $url = '/data/dtk-bang.html?r='.$rankType.'&p='. ($p + 1) .'&t=' .$total;
                return redirect($url);
            }
            if ($rankType >= 8) {
                break;
            }
            return redirect('/data/dtk-bang.html?r='.($rankType + 1).'&p=1&t=' .$total);
        }
        echo 'Import Success'. $total;
    }

    public function grabCategories()
    {
        $client = new \GetSuperCategory();
        $client->setAppKey($this->appKey);
        $client->setAppSecret($this->appSecret);
        $client->setVersion('v1.1.0');
        $result = $client->setParams([])->request();
        $resultData = json_decode($result, true);
        foreach ($resultData['data'] as $key=>$item) {
            //print_r($item);exit;
            $data['id'] = $item['cid'];
            $data['pic'] = $item['cpic'];
            $data['name'] = $item['cname'];
            $data['is_nav'] = 1;
            $this->categoryModel->insert($data);
            foreach ($item['subcategories'] as $subKey=>$subItem) {
                $subData['name'] = $subItem['subcname'];
                $subData['pic'] = $subItem['scpic'];
                $subData['parent_id'] = $item['cid'];
                $subData['id'] = $subItem['subcid'];
                $this->categoryModel->insert($subData);
            }
        }
        echo 'Success';
    }

    public function grabGoods() {
        set_time_limit(0);
        $data = $this->dtkService->getGoodsList();
        echo 'Add number:' .$data['addTotal'] . ' update number:'.$data['updateTotal'];
    }

    /**
     * 转换商品
     *
     * @param $item
     * @return array
     */
    private function convertGoods($item): array
    {
        $data['dtk_goods_id'] = $item['id'];
        $data['goods_id'] = $item['goodsId'];
        $data['title'] = $item['title'];
        $data['pic'] = $item['mainPic'];
        $data['pics'] = json_encode(array($item['marketingMainPic']));
        $data['short_title'] = $item['dtitle'];
        $data['original_price'] = $item['originalPrice'];
        $data['actual_price'] = $item['actualPrice'];
        $data['discounts'] = $item['discounts'];
        $data['commission_type'] = $item['commissionType'];
        $data['commission_rate'] = $item['commissionRate'];
        $data['coupon_link'] = $item['couponLink'];
        $data['coupon_total_num'] = $item['couponTotalNum'];
        $data['coupon_receive_num'] = $item['couponReceiveNum'];
        $data['month_sales'] = $item['monthSales'];
        $data['coupon_start_time'] = $item['couponStartTime'];
        $data['coupon_end_time'] = $item['couponEndTime'];
        $data['coupon_price'] = $item['couponPrice'];
        $data['item_link'] = $item['itemLink'];
        $data['sub_cid'] = $item['subcid'];
        $data['tb_cid'] = $item['tbcid'];
        $data['coupon_conditions'] = $item['couponConditions'];
        $data['daily_sales'] = $item['dailySales'];
        $data['two_hours_sales'] = $item['twoHoursSales'];
        $data['cid'] = $item['cid'];
        $data['desc'] = $item['desc'];
        $data['activity_type'] = $item['activityType'];
        $data['activity_start_time'] = $item['activityStartTime'];
        $data['activity_end_time'] = $item['activityEndTime'];
        $data['special_text'] = $item['specialText'];
        $data['hot_push'] = $item['hotPush'];
        $data['discount_full'] = $item['discountFull'];
        $data['discount_cut'] = $item['discountCut'];
        $data['seller_id'] = $item['sellerId'];
        $data['brand_id'] = $item['brandId'];
        return $data;
    }

    /**
     * 保存品牌
     *
     * @param $brandName
     * @param $brandId
     * @return mixed
     */
    private function saveBrand($brandName, $brandId) {
        $brand = $this->brandModel->where('name', $brandName)->find();
        if (!empty($brand) || is_null($brandName)) {
            return $brand['brand_id'];
        }
        $data['name'] = $brandName;
        $data['brand_id'] = $brandId;
        $this->brandModel->insert($data);
        return $brandId;
    }

    /**
     * 保存店铺
     *
     * @param $shopName
     * @param $sellerId
     * @param $shopType
     * @param $shopLogo
     * @param $shipScore
     * @param $serviceScore
     * @param $drsScore
     */
    private function saveShop($shopName, $sellerId, $shopType, $shopLogo, $shipScore, $serviceScore, $drsScore) {
        $shop = $this->shopModel->where('name', $shopName)->find();
        if (!empty($shop)) {
            return;
        }
        $data['name'] = $shopName;
        $data['seller_id'] = $sellerId;
        $data['type'] = $shopType;
        $data['logo'] = $shopLogo;
        $data['ship_score'] = $shipScore;
        $data['service_score'] = $serviceScore;
        $data['dsr_score'] = $drsScore;
        $this->shopModel->insert($data);
    }
}